<template>
<el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form-item label="问题标题" prop="questTitle">
            <el-input v-model="dataForm.questTitle" placeholder="问题标题"></el-input>
        </el-form-item>
        <el-form-item label="标签名称" prop="questName">
            <el-input v-model="dataForm.questName" placeholder="标签名称"></el-input>
        </el-form-item>
        <el-form-item label="是否置顶" prop="top">
            <el-select v-model="dataForm.top" placeholder="是否置顶">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
            <el-date-picker v-model="dataForm.time" type="datetime" placeholder="发布时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="发布状态">
                <el-option label="待审核" value="0"></el-option>
                <el-option label="审核中" value="1"></el-option>
                <el-option label="已发布" value="2"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="问题内容" prop="questContent">
            <el-input v-model="dataForm.questContent" placeholder="活动简介" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="活动图片" prop="img">
            <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :on-success="handleIconSuccess">
                <img v-if="dataForm.img" :src="replaceURl(dataForm.img)" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <a ref=""></a>
            </el-upload>
            <p class="formInfo">建议尺寸：100*100像素，jpg、png图片类型</p>
        </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
</el-dialog>
</template>


<script>
export default {
    data() {
        return {
            url: "",
            visible: false,
            dataForm: {
                id: undefined,
                questTitle: undefined,
                questName: undefined,
                status: undefined,
                allowRecover: undefined,
                userId: undefined,
                time: undefined,
                top: undefined,
                img: undefined,
                questContent: undefined,
            },
            uploadVisible: false,
            userId: "",
            username: "",
            dataRule: {
                questTitle: [{
                    required: true,
                    message: "问题标题不能为空",
                    trigger: "blur"
                }, ],
                questName: [{
                    required: true,
                    message: "标签名称不能为空",
                    trigger: "blur"
                }, ],
                status: [{
                    required: true,
                    message: "发布状态不能为空",
                    trigger: "blur"
                }, ],
                allowRecover: [{
                    required: true,
                    message: "是否允许回复不能为空",
                    trigger: "blur"
                }, ],
            },
        };
    },
    created() {
        this.getUserInfo();
    },
    methods: {
        replaceURl(url){
				return url.replace(/^"|"$/g, '');
			},
        init(id) {
            this.dataForm.id = id || 0;
            this.url = this.$http.adornUrl(
                `/sys/oss/upload?token=${this.$cookie.get("token")}`
            );
            this.visible = true;
            this.$nextTick(() => {
                this.$refs["dataForm"].resetFields();
                if (this.dataForm.id) {
                    this.$http({
                        url: this.$http.adornUrl(
                            `/admin/quest/info/${this.dataForm.id}`
                        ),
                        method: "get",
                    }).then(({
                        data
                    }) => {
                        if (data && data.code === 0) {
                            const info = data.result;
                            this.dataForm.questTitle = info.questTitle
                            this.dataForm.questName = info.questName
                            this.dataForm.status = info.status
                            this.dataForm.allowRecover = info.allowRecover
                            this.dataForm.userId = info.userId
                            this.dataForm.time = info.time
                            this.dataForm.id = info.id
                            this.dataForm.top = info.top
                            this.dataForm.img = info.img
                            this.dataForm.questContent = info.questContent
                        }
                    });
                }
            });
        },
        getUserInfo() {
            this.$http({
                url: this.$http.adornUrl('/sys/user/info'),
                method: 'get',
                params: this.$http.adornParams()
            }).then(({
                data
            }) => {
                if (data && data.code === 0) {
                    this.userId = data.user.userId
                    this.userName = data.user.username
                }
            })
        },
        // 表单提交
        dataFormSubmit() {
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    this.$http({
                        url: this.$http.adornUrl(
                            `/admin/quest/${!this.dataForm.id ? "save" : "update"}`
                        ),
                        method: "post",
                        data: this.$http.adornData({
                            questTitle: this.dataForm.questTitle,
                            questName: this.dataForm.questName,
                            status: this.dataForm.status,
                            allowRecover: this.dataForm.allowRecover,
                            time: this.dataForm.time,
                            top: this.dataForm.top,
                            img: this.dataForm.img,
                            questContent: this.dataForm.questContent,
                            id: this.dataForm.id,
                        }),
                    }).then(({
                        data
                    }) => {
                        if (data && data.code === 0) {
                            this.$message({
                                message: "操作成功",
                                type: "success",
                                duration: 1500,
                                onClose: () => {
                                    this.visible = false;
                                    this.$emit("refreshDataList");
                                },
                            });
                        } else {
                            this.$message.error(data.msg);
                        }
                    });
                }
            });
        },
        formatToLocalDateTime(dateTime) {
            const date = new Date(dateTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        handleIconSuccess(response) {
            this.dataForm.img = response.url;
            this.$forceUpdate();
        },
    },
};
</script>


<style lang="scss">
.formInfo {
    line-height: 0px;
    color: #999999;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>
